import fetch from "node-fetch";

//const voiceAPI1 = "http://frp-fit.top:42444/";
const voiceAPI1 = "http://frp-fit.top:16320/";
const voiceAPI2 = "https://api.lolimi.cn/API/yyhc/api.php";

export class Voice extends plugin {
    constructor() {
        super({
            name: "GSVI语音合成",
            dsc: "语音合成",
            event: "message",
            priority: 10,
            rule: [
                {
                    reg: ".+说.+",
                    fnc: "Voice"
                },
                {
                    reg: "#?语音(合成)?(角色)?列表$",
                    fnc: "VoiceList"
                }
            ]
        });
    }

    async Voice(e) {
        const msg = e.msg.split("说");
        let speaker = msg.shift().trim();
        const text = msg.join("说").replace("'", "").trim();


        let resp1 = await fetch(voiceAPI1 + "character_list");
        let characterList1 = await resp1.json();
        let characters1 = Object.keys(characterList1);

        if (characters1.includes(speaker)) {
            let url = voiceAPI1 + `tts?character=${speaker}&text=${text}`;
            await this.reply(segment.record(url));
        } else {
            logger.warn(`角色 ${speaker} 在第一个 API 中不存在，尝试第二个 API`);

            let resp2 = await fetch(`${voiceAPI2}?msg=${encodeURIComponent(text)}&sp=${encodeURIComponent(speaker)}`);
            let data2 = await resp2.json();
            if (data2.code === 200) {

                await this.reply(segment.record(data2.mp3));
            } else {
                logger.warn(`在第二个 API 中未找到角色 ${speaker} 或请求失败`);
                return false;
            }
        }
        return false;
    }

    async VoiceList() {
        let resp1 = await fetch(voiceAPI1 + "character_list");
        let characterList1 = Object.keys(await resp1.json());

        await this.reply(await Bot.makeForwardArray([
            "GSVI 语音合成角色列表",
            characterList1.join("\n")
        ]));
    }
}
